<?php

class OwnableBehavior extends ModelBehavior {

	var $settings = array();
	var $__user_id = null;

	function setup(&$model, $config = array()) {
		$default = array('field' => 'user_id', 'enabled' => true, 'session_user_id'=>'Auth.User.id');
		$this->settings[$model->name] = array_merge($default, (array)$config);
		// Get current user
		App::import("Helper", "Session");
    	$session = new SessionHelper();
		$this->__user_id = $session->read($this->settings[$model->name]['session_user_id']);
		//debug($this->__user_id);
		
	}

	function _config(&$model, $config = array()) {
		if (is_array($config)) {
			if (!empty($config)) {
				$this->settings[$model->name] = array_merge($this->settings[$model->name], $config);
			}
		} else {
			return $this->settings[$model->name][$config];
		}

		return $this->settings[$model->name];
	}

	function beforeFind(&$model, $conditions = array()) {
		extract($this->_config($model));
		
		if (!$enabled) {
			return $conditions;
		}
		
		if (empty($conditions['conditions'])) {
			$conditions['conditions'] = array(array($this->_fullField($model) => $this->__user_id));
		} else {
			$old_condition = $conditions['conditions'];
			$conditions['conditions'] = array($old_condition, array($this->_fullField($model) => $this->__user_id));
		}
		
		return $conditions;
	}
	function _fullField(&$model) {
		return $model->name . '.' . $this->_config($model, 'field');
	}
	function beforeSave(&$model) {
		extract($this->_config($model));
		if (!$enabled) {
			return true;
		}
		// fetch model since the user field is not in $model->data
		if(!isset($model->data[$model->name][$this->_config($model, 'field')])) {
			$org_data = $model->data;
			$user_id = $model->field($this->_fullField($model), $model->data[$model->name]['id']);
			if($user_id == $this->__user_id) {
				$return = true;
			} else {
				$return = false;
			}
			$model->data = $org_data;
			return $return;
		}
		
		if ($model->data[$model->name][$this->_config($model, 'field')] != $this->__user_id) {
			return false;
		}
		return true;
	}
	
	function beforeDelete(&$model, $cascade = true) {
		extract($this->_config($model));
		if (!$enabled) {
			return true;
		}
		$user_id = $model->field($this->_fullField($model), $model->id);
		if($user_id == $this->__user_id) {
			$return = true;
		} else {
			$return = false;
		}
	}

}

?>